package com.yifan.concurrency.ch2;

import net.jcip.annotations.GuardedBy;
import net.jcip.annotations.ThreadSafe;

import javax.servlet.*;
import java.io.IOException;
import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 程序清单 2-6 这个 servlet 能正确地缓存最新的计算结果，但并发性却非常差 不要这么做
 */
@ThreadSafe
public class SynchronizedFactorizer implements Servlet {

    @GuardedBy("this")
    private BigInteger lastNumber;

    @GuardedBy("this")
    private BigInteger[] lastFactors;

    public void init(ServletConfig config) throws ServletException {

    }

    public ServletConfig getServletConfig() {
        return null;
    }

    public synchronized void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        BigInteger i = extractFromRequest(req);
        if (i.equals(lastNumber)) {
            encodeIntoResponse(res, lastFactors);
        } else {
            BigInteger[] factors = factor(i);
            lastNumber = i;
            lastFactors = factors;
            encodeIntoResponse(res, factors);
        }
    }

    private BigInteger[] factor(BigInteger i) {
        //todo
        return null;
    }

    private void encodeIntoResponse(ServletResponse res, BigInteger[] bigIntegers) {
    }

    private BigInteger extractFromRequest(ServletRequest req) {
        //todo
        return null;
    }

    public String getServletInfo() {
        return null;
    }

    public void destroy() {

    }
}
